//
//  FFLogManager.m
//  FFSurveillance
//
//  Created by roro_latrobe on 16/10/29.
//  Copyright © 2016年 cn.wanda. All rights reserved.
//

#import "FFLogManager.h"
#import "FFLogConfigFactory.h"
#import "FFLogFormatter.h"
#import "FFLogFileFormatter.h"
#import "MongooseDaemon.h"
#import "PTEDashboard.h"
#import "PTEConsoleTableView.h"

//int ddLogLevel = LOG_LEVEL_VERBOSE;


@interface FFLogManager()<FFLogFormatterDelegate>
{
    FFLogFormatter *_ttyFilter;//控制台过滤器
//    AriderLogComponetView *_logComponetView;
    MongooseDaemon *_remoteServer;
}
@end

#define IP_PORT @"1688"

@implementation FFLogManager

+ (void)setup{
    [[FFLogManager sharedManager] setupAll];
}

+ (FFLogManager *)sharedManager{
    static FFLogManager *kInstance = nil;
    @synchronized(self){
        if(!kInstance){
            kInstance = [[FFLogManager alloc] init];
        }
    }
    return kInstance;
}
- (id)init{
    self = [super init];
    if(self){//这里不应该调用setup,否则会造出无限递归
        
    }
    return self;
}

- (void)setupAll{
    [self setupDefaultValue];
    [self setupLogger];
    [self setupStdErrorLog];
//    [self setupLogView];
    
    
}

- (void)setupLogger{
    [DDLog addLogger:[DDASLLogger sharedInstance]];//system
    
    [DDLog addLogger:[DDTTYLogger sharedInstance]];//控制台
    _ttyFilter = [[FFLogFormatter alloc] init];
    _ttyFilter.formatterDelegate = self;
    [[DDTTYLogger sharedInstance] setLogFormatter:_ttyFilter];
    
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    FFLogFileFormatter *fileFormatter = [[FFLogFileFormatter alloc] init];
    [fileLogger setLogFormatter:fileFormatter];
    [DDLog addLogger:fileLogger];//文件

}

- (void)setupColor{
    [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
    
    char *xcode_colors = getenv("XcodeColors");
    if (xcode_colors && (strcmp(xcode_colors, "YES") == 0))
    {
        // XcodeColors is installed and enabled!
//        NSLog(@"XcodeColors enabled");
    }
}

- (void)showLogWindow {
   PTEDashboard *dashboard = [PTEDashboard sharedDashboard];
    [dashboard show];
    dashboard.maximized = YES;
}

- (void)setupDefaultValue{
    self.logConfig.filterFileNameSet = [[NSMutableSet alloc] init];
    self.logConfig.filterMethodNameSet = [[NSMutableSet alloc] init];
    self.logConfig.saveFileNameSet = [[NSMutableSet alloc] init];
    self.logConfig.saveMethodNameSet = [[NSMutableSet alloc] init];
    self.logConfig.isCaseInsensitive = YES;
    //    self.isShowFunctionName = YES;
    //    self.isShowFileName = YES;
    self.logConfig.isShowTime = YES;
    self.logConfig.isWriteLogIntoFile = YES;
}
//
- (void)setupStdErrorLog{
    if (!isatty(STDERR_FILENO)){//如果没有联机调试
        [self writeSysLogIntoFile];
    }else{//联机就没必要写入文件了.提高效率
        self.logConfig.isWriteLogIntoFile = NO;
    }
}

#pragma mark file log
//将非通过宏调用的log日志重定向到文件. 怎么和ALog文件合并?
- (void)writeSysLogIntoFile{
    NSString *logDirectory = [self defaultLogsDirectory];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *suffix = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"cmd_%@.log", suffix];
    NSString *logPath = [logDirectory stringByAppendingPathComponent:fileName];
    freopen([logPath UTF8String], "a+", stderr);
}

- (NSString *)defaultLogsDirectory
{
#if TARGET_OS_IPHONE
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *baseDir = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSString *logsDirectory = [baseDir stringByAppendingPathComponent:@"Logs"];
    
#else
    NSString *appName = [[NSProcessInfo processInfo] processName];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
    NSString *logsDirectory = [[basePath stringByAppendingPathComponent:@"Logs"] stringByAppendingPathComponent:appName];
    
#endif
    return logsDirectory;
}


#pragma mark FFLogFormatterDelegate
- (void)FFLogFormatter:(FFLogFormatter *)formatter orginalLogMessage:(DDLogMessage *)logMessage formattedText:(NSString *)formattedText{
//    [_logComponetView.logDisplayView addText:formattedText textColor:nil];
}

#pragma mark function

- (void)clearDisplayLog{
//    [_logComponetView.logDisplayView clearText];
}

#pragma mark property
- (void)setIsRemoteAccess:(BOOL)isRemoteAccess{
    self.logConfig.isRemoteAccess = isRemoteAccess;
    if(isRemoteAccess){
        _remoteServer = nil;
        _remoteServer = [[MongooseDaemon alloc] init];
        [_remoteServer startMongooseDaemon:IP_PORT];
    }else{
        [_remoteServer stopMongooseDaemon];
    }
}

- (NSString *)remoteAccessIPAddress{
    return [NSString stringWithFormat:@"http://%@:%@", [_remoteServer getIPAddress], IP_PORT];
}


- (FFLogConfig *)logConfig {
    if(!_logConfig) {
        _logConfig = [FFLogConfig new];
    }
    return _logConfig;
}

@end
